//
//  String++.swift
//
//
//  Created by S JZ on 2023/12/6.
//

import Foundation

// 将String转换成NSString，做一些NSString简单的操作
public extension String {
    public var nsString: NSString { return self as NSString }
    
    // MARK: - 将字符串转为字符型
    public var doubleValue: Double {
        self.nsString.doubleValue
    }
    
    public var floatValue: Float {
        self.nsString.floatValue
    }
    
    public var intValue: Int {
        self.nsString.integerValue
    }
    
    public var boolValue: Bool {
        self.nsString.boolValue
    }
    
    // MARK: - 获取子字符串，通过转为NSString
    @discardableResult
    public func subString(form: Int) -> String {
        guard self.count > form else { return "" }
        return self.nsString.substring(from: form)
    }
    
    @discardableResult
    public func subString(to: Int) -> String {
        guard self.count > to else { return "" }
        return self.nsString.substring(to: to)
    }
    
    @discardableResult
    public func subString(with range: NSRange) -> String {
        guard self.count > range.upperBound, range.lowerBound >= 0 else { return "" }
        return self.nsString.substring(with: range)
    }
    
    // MARK: - 下标
    public subscript(bounds: CountableRange<Int>) -> String {
        guard self.count > bounds.upperBound, bounds.lowerBound >= 0 else { return "" }
        let start = index(startIndex, offsetBy: bounds.lowerBound)
        let end = index(startIndex, offsetBy: bounds.upperBound)
        let str = self[start..<end]
        return String(str)
    }
    
    public subscript(bounds: CountableClosedRange<Int>) -> String {
        guard self.count > bounds.upperBound, bounds.lowerBound >= 0 else { return "" }
        let start = index(startIndex, offsetBy: bounds.lowerBound)
        let end = index(startIndex, offsetBy: bounds.upperBound)
        let str = self[start...end]
        return String(str)
    }
    
    public subscript(index: Int) -> String {
        guard self.count > index else { return "" }
        let character = self[self.index(startIndex, offsetBy: index)]
        return String(character)
    }
}


